<template>
    <div class="common-layout">
        <el-container>
            <!-- <el-header style="display: flex; align-items: center;">
                <div class="item-text" style="flex: 1;"></div>
                <div style="flex: 1;">
                    <el-row align="middle" :gutter="20" justify="start">
                        <el-col :span="8">
                            <el-input v-model="searchModel.ProductPlanCode" placeholder="生产计划编号或编码" clearable
                                style="width: 240px; height: 35px; font-size: 15px; padding: 0 15px;"
                                @keyup.enter.native="SearchList" />
                        </el-col>
                        <el-col :span="4" style="display: flex; align-items: center; justify-content: flex-start;">
                            <el-button type="primary" @click="SearchList"
                                style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                                <i class="el-icon-search"></i>搜索
                            </el-button>
                        </el-col>
                        <el-col :span="4" style="display: flex; align-items: center; justify-content: flex-start;">
                            <el-button type="success" @click="SearchList"
                                style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                                <i class="el-icon-refresh"></i>刷新
                            </el-button>
                        </el-col>
                        <el-col :span="4" style="display: flex; align-items: center; justify-content: flex-start;">
                            <el-button type="success" @click="InsertData()"
                                style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                                <i class="el-icon-plus"></i>新增
                            </el-button>
                        </el-col>
                    </el-row>
                </div>
            </el-header> -->

            <div class="view-header" style="display: flex; justify-content: space-between;margin-top: 15px;">
                <div class="desc-text">
                    <i class="el-icon-s-grid" />
                    <span>生产计划列表</span>
                </div>
                <div>
                   <el-input v-model="searchModel.ProductPlanCode" placeholder="生产计划编号或编码" clearable
                                style="width: 240px; height: 35px; font-size: 15px; padding: 0 15px;"
                                @keyup.enter.native="SearchList" />
                    <el-button type="primary" @click="SearchList">
                        <i class="el-icon-search"></i>搜索
                    </el-button>
                    <el-button type="success" @click="SearchList">
                        <i class="el-icon-refresh"></i>刷新
                    </el-button>
                    <el-button type="success" @click="InsertData()">
                        <i class="el-icon-plus"></i>新增
                    </el-button>
                </div>
            </div>


            <!-- <el-main style="display: flex; flex-direction: column; gap: 30px;"> -->
            <div class="mian-flex">
                <!-- 订单列表 -->
                <div class="table-info mes-table" v-loading="loading">
                    <!-- <div class="table-container"> -->
                    <!-- <div class="section-title">生产计划列表</div> -->

                    <!--  生产计划数据表 -->
                    <el-table :data="detailTableData" style="width: 100%;" stripe="true" border="true" max-height="550">
                        <el-table-column type="index" width="50" />
                        <el-table-column type="selection" width="50" align="center" />
                        <el-table-column label="单据编号" prop="productPlanCode" width="250" align="center">
                            <template #default="scope">
                                <el-link type="primary" @click="showOrderDetail(scope.row)">
                                    {{ scope.row.productPlanCode }}
                                </el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="workOrderCode" label="工单编号" width="180" align="center" />
                        <el-table-column prop="inventoryName" label="存货名称" width="180" align="center" />
                        <el-table-column prop="inventoryCode" label="存货编码" width="180" align="center" />
                        <el-table-column prop="saleOrderCode" label="销售订单编号" width="180" align="center" />
                        <el-table-column
                            label="订单类型"
                            prop="orderType"
                            min-width="120"
                            align="center"
                        >
                            <template #default="scope">
                              <span v-if="scope.row.orderType === 0">加工</span>
                              <span v-else-if="scope.row.orderType === 1">返工</span>
                              <span v-else></span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="质检单号"
                            prop="productInspectionCode"
                            min-width="180"
                            align="center"
                        />
                        <el-table-column prop="qty" label="计划数" width="120" align="center" />
                        <el-table-column prop="finishQty" label="完工数" width="120" align="center" />
                        <el-table-column prop="remark" label="备注" width="400" align="center" />
                        <el-table-column prop="createDate" label="创建时间" width="250" align="center" />
                        <el-table-column prop="creator" label="创建人" width="180" align="center" />
                        <el-table-column
                            fixed="right"
                            label="操作"
                            width="60"
                            align="center"
                        >
                            <template #default="scope">
                              <el-popconfirm
                                    placement="bottom-end"
                                    popper-class="my-popper-delete"
                                    title="是否确认删除该行数据"
                                    @confirm="deleteChange(scope.row)"
                                >
                                    <template #reference>
                                        <span style="color: #f54346; cursor: pointer;">删除</span>
                                    </template>
                                </el-popconfirm>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="demo-pagination-block table-pagination"
                        style="display: flex; justify-content: flex-end;">
                        <el-pagination v-model:current-page="inventoryCurrentPage" v-model:page-size="inventoryPageSize"
                            :page-sizes="[15, 30, 50, 80, 100]" layout="total, sizes, prev, pager, next, jumper"
                            :total="inventoryTotal" @current-change="handleCurrentChange"
                            @size-change="handleSizeChange" />
                    </div>

                </div>
            </div>

            <!-- 生产计划明细弹窗 -->
            <el-dialog v-model="detailDialogVisible" class="order-detail-dialog" :lock-scroll="true" width="80%"
                :before-close="handleClose">
                <!-- 自定义标题 -->
                <template #title>
                    <div style="display: flex; flex-direction: column;">
                        <span style="font-size: 20px; font-weight: bold;">生产计划明细</span>
                    </div>
                </template>
                <!-- 上部分表单 -->
                <el-form :model="productPlanHeader" label-width="120px" class="order-detail-form"
                    label-position="right">
                    <el-row :gutter="20">
                        <el-col :span="22">
                            <el-form-item label="单据编号:">
                                <el-input v-model="productPlanHeader.productPlanCode" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="22">
                            <el-form-item label="销售订单编号:">
                                <el-input v-model="productPlanHeader.saleOrderCode" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="22">
                            <el-form-item label="订单类型:">
                                <el-input v-model="productPlanHeader.orderType" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="22">
                            <el-form-item label="质检单号">
                                <el-input v-model="productPlanHeader.productInspectionCode" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="22">
                            <el-form-item label="备注">
                                <el-input v-model="productPlanHeader.remark" type="textarea" disabled />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <!-- 分割线 -->
                <div style="margin: 10px 0; border-bottom: 1px solid #dcdfe6;"></div>

                <!-- 下部分：订单明细表格 -->
                <div class="detail-table-wrapper">
                    <el-table :data="uniqueProductPlanDetails" style="width: 100%;" stripe border height="400">
                        <el-table-column type="selection" width="35" />
                        <el-table-column label="存货编号" min-width="200">
                            <template #default="scope">
                                <!-- {{ getInventoryCode(scope.row.inventoryId) }} -->
                                <span v-if="scope.row.inventory_Id === 0" style="color: red;"></span>
                                <span v-else>{{ scope.row.inventoryCode }}</span>
                            </template>
                        </el-table-column>

                        <el-table-column label="存货名称" min-width="150">
                            <template #default="scope">
                                <span v-if="scope.row.inventory_Id === 0" style="color: red;"></span>
                                <span v-else>{{ scope.row.inventoryName }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="SpecificationModel" label="存货规格" width="160" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.SpecificationModel === null" style="color: red;"></span>
                                <span v-else>{{ scope.row.SpecificationModel }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="workOrderCode" label="工单编号" width="200" />
                        <el-table-column prop="qty" label="数量" width="100" />
                        <el-table-column prop="finishQty" label="完成数" width="100" />
                        <el-table-column prop="createDate" label="创建时间" width="120" />
                        <el-table-column prop="creator" label="创建人" width="100" />
                    </el-table>
                </div>

                <template #footer>
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                </template>
            </el-dialog>

            <!-- 新增数据弹窗 -->
            <el-dialog v-model="insertDialogVisiable" class="fixed-size-dialog" width="80%"
                :before-close="handleInsertClose">
                <!-- 自定义标题插槽 -->
                <template #title>
                    <div style="display: flex; flex-direction: column;">
                        <span style="font-size: 20px; font-weight: bold;">新增生产计划</span>
                        
                    </div>
                </template>

                <!-- 上半部分表单 -->
                <div class="dialog-body">
                    <div class="form-section">
                        <el-form :model="insertForm" label-width="120px" class="order-detail-form"
                            label-position="right">
                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="单据编号" width="150">
                                        <el-input v-model="insertForm.code" type="text" placeholder="请输入单据编号"
                                            style="width: 100%" />
                                    </el-form-item>
                                </el-col>

                                <!-- 销售订单编号 -->
                                <el-col :span="24">
                                    <el-form-item label="销售订单编号" prop="qualityDetectionProjectId">
                                        <el-select
                                            v-model="insertForm.saleOrderId"
                                            placeholder="请选择销售订单编号"
                                            filterable
                                            :filter-method="querySearchAsync"
                                            @change="handleSelect"
                                            @visible-change="visibleHandler"
                                            style="width: 100%;"
                                        >
                                            <el-option
                                            v-for="item in saleOrderTemp"
                                            :key="item.id"
                                            :label="item.code"
                                            :value="item.id"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </el-col>

                                <el-col :span="24">
                                    <el-form-item label="备注" width="150">
                                        <el-input v-model="insertForm.remark" type="textarea" placeholder="填写备注"
                                            style="width: 100%" />
                                    </el-form-item>
                                </el-col>

                            </el-row>
                        </el-form>
                    </div>
                </div>

                <!-- 分割线 -->
                <div style="margin: 10px 0; border-bottom: 1px solid #dcdfe6;"></div>

                <!-- 下半部分：可新增数据的表格 -->
                <div class="table-section">
                    <!-- <el-button type="primary" @click="addRow" style="margin-bottom: 10px;">新增一行</el-button> -->
                    <el-table :data="insertTableData" style="width: 100%;" border stripe>
                        <el-table-column type="index" label="序号" width="50" />

                        <el-table-column label="产品" width="220">
                            <template #default="scope">
                                <el-input v-model="scope.row.inventoryName" readonly
                                    @click="openInventoryDialog(scope.row), loadingInventoryData()"
                                    placeholder="选择产品" />
                            </template>
                        </el-table-column>

                        <el-table-column prop="inventoryCode" label="产品编号" width="260" />
                        <el-table-column prop="specificationModel" label="产品规格" width="300" />
                        <!-- <el-table-column prop="WorkOrderCode" label="工单编号" width="250" /> 如果有 -->
                        <el-table-column prop="quantity" label="数量" width="200">
                            <template #default="scope">
                                <el-input v-model.number="scope.row.quantity" type="text" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="FinishedProduct" label="完成数" width="200" />
                        <!-- <el-table-column label="操作" width="100">
                            <template #default="scope">
                                <el-button type="danger" @click="removeRow(scope.$index)" size="small">删除</el-button>
                            </template>
                        </el-table-column> -->
                    </el-table>
                </div>

                <template #footer>
                    <el-button @click="insertDialogVisiable = false">取消</el-button>
                    <el-button type="primary" @click="saveInsert">保存</el-button>
                </template>
            </el-dialog>

            <!-- 存货选择弹窗 -->
            <el-dialog v-model="inventoryDialogVisible" width="1200px" :close-on-click-modal="false"
                :destroy-on-close="true" top="5vh" class="fixed-inventory-dialog">
                <template #title>
                    <span style="font-weight: bold;">选择存货</span>
                    
                </template>

                <div style="display: flex; justify-content: flex-end; margin-bottom: 10px;">
                    <el-input v-model="inventorySearchData.Code" placeholder="产品编号或名称" clearable
                        style="width: 240px; height: 35px; font-size: 15px; padding: 0 15px;"
                        @keyup.enter.native="handleSearch" />

                    <el-button type="primary" @click="handleSearch"
                        style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                        搜索
                    </el-button>
                </div>

                <!-- 表格滚动容器 -->
                <div class="table-scroll-wrapper">
                    <el-table :data="inventoryOptions" stripe border style="width: 100%;"
                        @selection-change="handleSelectionChange">
                        <!-- 序号列 -->
                        <el-table-column type="index" width="50" />
                        <!-- 选择列 -->
                        <el-table-column type="selection" width="50"
                            :selectable="(row, index) => !!row.processLineName" align="center" />
                        <el-table-column prop="inventoryCode" label="产品编号" width="250" />
                        <el-table-column prop="inventoryName" label="产品名称" width="220" />
                        <el-table-column prop="unitName" label="单位" width="120" />
                        <el-table-column prop="specificationModel" label="产品规格" width="290" />
                        <el-table-column prop="processLineName" label="工艺路线" width="180" />
                    </el-table>
                </div>

                <!-- 分页部分 -->
                <div class="demo-pagination-block" style="display: flex; justify-content: flex-end; margin-top: 20px;">
                    <el-pagination v-model:current-page="inventoryCurrentPage" v-model:page-size="inventoryPageSize"
                        :page-sizes="[15, 30, 50, 80, 100]" layout="total, sizes, prev, pager, next, jumper"
                        :total="totalCount" @current-change="handleCurrentChangeInventory"
                        @size-change="handleSizeChangeInventory" />
                </div>

                <!-- 底部按钮 -->
                <template #footer>
                    <div style="text-align: right;">
                        <el-button @click="inventoryDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="confirmInventory">确定</el-button>
                    </div>
                </template>
            </el-dialog>


        </el-container>
    </div>
</template>

<script setup>
import { ref, watch, onMounted, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
    getWareHouse,
    getInventory,
    getDepemendents,
    getEmployees,
    getExistingQuantity,
    ProductPlanSearch,
    addProduct,
    ProductPlanSearchListDetail,
    GetProductPlanCode,
    deleteProductionProductPlan,
    SaleInfoSearch
} from '../../extension/V2/ProductPlan'

// 搜索条件模型
const searchModel = ref({ ProductPlanCode: '' })

// 表格数据与分页数据
const detailTableData = ref([]) // 订单展示明细模型
const detailDialogVisible = ref(false)
const orderDetail = ref({})
const productPlanDetail = ref({})
const insertDialogVisiable = ref(false)
let loading = false

const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(15)

// 存货分页
const inventoryCurrentPage = ref(1)
const inventoryPageSize = ref(15)
const inventoryTotal = ref(0)

const orderInfodetail = ref([])

const productPlanHeader = ref({})
const productPlanDetails = ref([])




// 新增表单
const insertForm = ref({
    code: '',
    inventoryId: '',
    quantity: '',
    orderNo: '',
    businessType: '',
    workshop: '',
    receiver: '',
    warehouseName: '',
    remark: '',
    saleOrderId: null
})

// 新增表格数据
const insertTableData = ref([
    {
        inventoryName: '',       // 产品名称--存货
        inventoryId: '',
        inventoryCode: '',       // 产品编号--存货
        specificationModel: '',   // 产品规格--存货
        quantity: '',     // 数量
        FinishedProduct: '',  // 完成数
        CreateDate: '',       // 创建时间
        CreateID: '',            // 创建人id
        Creator: '',           // 创建人
        Modifier: '',          // 修改人
        ModifyDate: '',       // 修改时间
    }
])

// 添加行
const addRow = () => {
    insertTableData.value.push({
        inventoryName: '',       // 产品名称--存货
        inventoryId: '',
        inventoryCode: '',       // 产品编号--存货
        specificationModel: '',   // 产品规格--存货
        quantity: '',     // 数量
        FinishedProduct: '',  // 完成数
        CreateDate: '',       // 创建时间
        CreateID: '',            // 创建人id
        Creator: '',           // 创建人
        Modifier: '',          // 修改人
        ModifyDate: '',       // 修改时间
    })
}


// 删除行
const removeRow = (index) => {
    insertTableData.value.splice(index, 1)
}

// 自动获取生产计划单据编号
const getProductPlanCode = async () => {
    try {
        const res = await GetProductPlanCode()
        if (res && res.data) {
            insertForm.value.code = res.data
        }
    } catch (err) {
        console.error('获取生产计划编号失败:', err)
        ElMessage.error('获取生产计划编号失败')
    }
}

const saleOrderTemp = ref([])
const saleOrderData = ref([])
// 获取销售订单列表
const getSaleOrderList = async () => {
    const params ={
        Code: '',
        page: 1,
        rows: 10000
    }
    try {
        const result = await SaleInfoSearch(params)
        if (result.status === 0) {
            saleOrderData.value = result.rows || []
            saleOrderTemp.value = result.rows || []
        } else {
            saleOrderData.value = []
            ElMessage.error(result.msg || '查询失败')
        }
    } catch (error) {
        console.error('查询异常:', error)
    }
}
const visibleHandler = ()=> {
    saleOrderTemp.value = saleOrderData.value;
}
// 对数据进行模糊匹配
const  querySearchAsync = (queryString)=> {
    saleOrderTemp.value = saleOrderData.value.filter(
      (item) =>
        item.code.includes(queryString)
    );
}
const  handleSelect = (id)=> {
    console.log('当前所选质检指标所属项目ID：', id);
}

// 保存新增
const saveInsert = async () => {

    console.log("保存前的 insertForm:", insertForm.value)
    console.log("保存前的 insertTableData:", insertTableData.value)
    try {
        // 构造请求参数
        const payload = {
            code: insertForm.value.code || "",     // 单据编号
            remark: insertForm.value.remark || "",   // 备注
            saleOrderId: insertForm.value.saleOrderId, // 销售订单ID
            productionProductPlanDetails: insertTableData.value.map(row => {
                return {
                    inventoryId: row.inventoryId,  // 存货ID
                    quantity: row.quantity          // 数量
                }
            })
        }
        if (payload.productionProductPlanDetails.length === 0) {
            ElMessage.error('至少新增一条产品')
            return
        }
        if (!payload.code) {
            ElMessage.error('请填写单据编号和备注')
            return
        }
        if (payload.productionProductPlanDetails.some(row => !row.quantity) || payload.productionProductPlanDetails.some(row => !row.inventoryId)) {
            ElMessage.error('请填写产品和数量')
            return
        }
        console.log('请求参数 payload:', payload)

        // 调用新增接口
        const res = await addProduct(payload)
        console.log("接口返回 res:", res)

        if (res) {
            ElMessage.success('新增保存成功')
            insertDialogVisiable.value = false
            handleInsertClose() // 关闭时清空数据
            SearchList()
        } else {
            ElMessage.error(res.msg || '保存失败')
        }
    } catch (err) {
        console.error('保存异常:', err)
        ElMessage.error('保存异常')
    }
}


// 删除操作
const deleteChange = async (val) => {
    console.log('当前选中信息：', val.productPlan_Id);
    const oldCurrentPage = inventoryCurrentPage.value;
    const temp = Math.ceil(
    (inventoryTotal.value - (inventoryTotal.value - 1)) / pageSize.value
    );
    if (inventoryCurrentPage.value > temp) {
        inventoryCurrentPage.value = temp;
    }
    try {
      const params = {
        id: val.productPlan_Id || "", // 生产计划id
      };
      const res = await deleteProductionProductPlan(params);
      if (res.ok) {
        ElMessage.success("删除成功");
        SearchList()
      } else {
        inventoryCurrentPage.value = oldCurrentPage;
        ElMessage.error((res.err&&res.err.msg) || "删除失败");
      }
    } catch (err) {
      inventoryCurrentPage.value = oldCurrentPage;
      ElMessage.error((err.err&&err.err.msg) || "删除失败");
    }
}

// 关闭时清空数据
const handleInsertClose = () => {
    Object.assign(insertForm.value, {
        code: '',
        remark: '',
        businessType: '',
        workshop: '',
        receiver: '',
        warehouseName: '',
        saleOrderId: null
    })
    insertTableData.value = [{
        inventoryName: '',       // 产品名称--存货
        inventoryId: '',
        inventoryCode: '',       // 产品编号--存货
        specificationModel: '',   // 产品规格--存货
        quantity: '',     // 数量
        FinishedProduct: '',  // 完成数
        CreateDate: '',       // 创建时间
        CreateID: '',            // 创建人id
        Creator: '',           // 创建人
        Modifier: '',          // 修改人
        ModifyDate: '',       // 修改时间
    }]
    insertDialogVisiable.value = false
}

//新增窗口
const InsertData = async () => {
    insertDialogVisiable.value = true
    await getProductPlanCode()   // 获取单号
    await getSaleOrderList() // 获取销售订单
}

// 仓库数据
const warehouseOptions = ref([])
const departmentOptions = ref([])
const employeeOptions = ref([])


// 仓库数据下拉展示
const loadWarehouses = async () => {
    try {
        console.log("111仓库数据加载")
        const result = await getWareHouse()
        // 假设后端返回 { status: 0, rows: [...] }
        if (result.status === 0) {
            warehouseOptions.value = result.rows || []
        } else {
            ElMessage.error(result.msg || '获取仓库数据失败')
        }
    } catch (err) {
        console.error('获取仓库数据异常:', err)
    }
}

// 部门数据下拉展示
const loadDepartment = async () => {
    try {
        console.log("111部门数据加载")
        const result = await getDepemendents()
        // 假设后端返回 { status: 0, rows: [...] }
        if (result.status === 0) {
            departmentOptions.value = result.rows || []
        } else {
            ElMessage.error(result.msg || '获取部门数据失败')
        }
    } catch (err) {
        console.error('获取部门数据异常:', err)
    }
}

// 员工数据下拉展示
const loadEmployees = async () => {
    try {
        console.log("111员工数据加载")
        const result = await getEmployees()
        // 假设后端返回 { status: 0, rows: [...] }
        if (result.status === 0) {
            employeeOptions.value = result.rows || []
        } else {
            ElMessage.error(result.msg || '获取员工数据失败')
        }
    } catch (err) {
        console.error('获取员工数据异常:', err)
    }
}

// 获取计量单位数据
const loadUnit = async () => {
    const result = await getUnit()
}


// 存货选择弹窗处理
// 弹窗开关
const inventoryDialogVisible = ref(false)
// 存货列表数据
const inventoryOptions = ref([])
// 当前选中的存货（单选）
const selectedInventory = ref([])
// 当前正在编辑的订单行
const currentRow = ref(null)

// 获取搜索参数
const getProductParams = () => {
    const wheresArr = []
    if (inventorySearchData.Code) {
        wheresArr.push({
            name: 'inventoryCode',       // 搜索字段名
            value: String(inventorySearchData.Code || ''),
            displayType: 'like'          // 模糊匹配
        })
    }

    return {
        page: inventoryCurrentPage.value,
        rows: inventoryPageSize.value,
        sort: 'CreateDate',
        order: 'desc',
        wheres: JSON.stringify(wheresArr)  // 转为 JSON 字符串
    }
}


//加载数据
const loadingInventoryData = async () => {
    try {
        const params = getProductParams()
        console.log("数据加载getInventory()")
        const res = await getInventory(params)
        console.log("数据加载成功getInventory（）", res)
        inventoryOptions.value = res.rows || []
        totalCount.value = res.total || 0   // 更新总条数
    } catch (err) {
        console.error('加载存货数据异常:', err)
    }
}

const getInventoryCode = (id) => {
    const item = inventoryOptions.value.find(opt => opt.id === id)
    return item ? item.inventoryCode : ''
}

const getInventoryName = (id) => {
    const item = inventoryOptions.value.find(opt => opt.id === id)
    return item ? item.inventoryName : ''
}

onMounted(() => {
    loadWarehouses()
    loadDepartment()
    loadEmployees()
    loadingInventoryData()
    // getInventoryUnit()
    // loadUnit()
})

// 打开弹窗并加载产品数据
const openInventoryDialog = async (row) => {
    currentRow.value = row
    inventoryDialogVisible.value = true
    currentPage.value = 1   // 打开时回到第一页
}

// 分页页码变化
const handleCurrentChangeInventory = (page) => {
    inventoryCurrentPage.value = page
    loadingInventoryData()
    // Search()
}

// 分页每页条数变化
const handleSizeChangeInventory = (rows) => {
    console.log("页大小变化:", rows)
    inventoryPageSize.value = rows
    inventoryCurrentPage.value = 1
    loadingInventoryData()
    console.log("页大小变化pageSize.value:", pageSize.value)
}

const inventorySearchData = reactive({
    Code: ''
}) // 用户输入的搜索内容

const handleSearch = () => {
    // 调用加载方法
    currentPage.value = 1   // 搜索时回到第一页
    loadingInventoryData()
}

// 表格勾选事件（这里用单选，所以取第一条）
const handleSelectionChange = (val) => {
    selectedInventory.value = val
}

// 仓库或存货变化时调用
const onWarehouseOrInventoryChange = async (row) => {
    console.log("仓库或存货变化时调用")

    // 找到仓库和存货对象（用于显示名称等）
    const warehouse = warehouseOptions.value.find(w => w.id === row.warehouseId)
    const inventory = inventoryOptions.value.find(i => String(i.id) === String(row.inventoryId))

    console.log("仓库:", warehouse)
    console.log("存货:", inventory)

    if (!warehouse || !inventory) {
        console.log("没选仓库或存货就返回")
        row.existingQuantity = ''
        return
    }

    // 调用后端接口，直接传 ID
    console.log("执行调用 getExistingQuantity()")
    const res = await getExistingQuantity({ warehouseId: row.warehouseId, inventoryId: row.inventoryId })

    if (res && res.ok) {
        row.existingQuantity = res.data // 后端返回的现存量
        console.log("返回的现存量:", row.existingQuantity)
    } else {
        row.existingQuantity = '' // 查不到时清空
    }

    // 保证显示名称
    row.warehouseName = warehouse.warehouseName
    row.inventoryName = inventory.inventoryName
}



// 确认选择
const confirmInventory = () => {
    if (!selectedInventory.value || selectedInventory.value.length === 0) {
        ElMessage.warning("请选择至少一条存货")
        return
    }
    if(selectedInventory.value.length !== 1) {
        return ElMessage.warning("只能选择一条存货")
    }

    // 当前行
    if (currentRow.value) {
        // 第一条存货回填到当前行
        const first = selectedInventory.value[0]

        currentRow.value.inventoryName = first.inventoryName
        currentRow.value.inventoryId = first.id
        currentRow.value.inventoryCode = first.inventoryCode
        currentRow.value.specificationModel = first.specificationModel
        currentRow.value.quantity = first.InventoryQty
        currentRow.value.FinishedProduct = first.FinishedProduct
        currentRow.value.CreateDate = first.CreateDate
        currentRow.value.Creator = first.Creator

        // onWarehouseOrInventoryChange(currentRow.value)

        // 剩余选中存货新增行
        for (let i = 1; i < selectedInventory.value.length; i++) {
            const item = selectedInventory.value[i]
            insertTableData.value.push({
                inventoryName: item.inventoryName,
                inventoryId: item.id,
                inventoryCode: item.inventoryCode,
                specificationModel: item.specificationModel,
                WorkOrderCode: item.WorkOrderCode,
                quantity: item.quantity,
                FinishedProduct: item.FinishedProduct,
                CreateDate: item.CreateDate,
                Creator: item.Creator,
                Modifier: item.Modifier,
                ModifyDate: item.ModifyDate
            })
        }
    }

    inventoryDialogVisible.value = false
    selectedInventory.value = [] // 清空已选
}

const getParams = () => ({
    ProductPlanCode: searchModel.value.ProductPlanCode,
    page: inventoryCurrentPage.value,
    rows: inventoryPageSize.value
})

// 分页页码变化
const handleCurrentChange = (page) => {
    inventoryCurrentPage.value = page
    Search()
}

// 分页每页条数变化
const handleSizeChange = (size) => {
    inventoryPageSize.value = size
    inventoryCurrentPage.value = 1
    Search()
}

// 查询方法（分页变化，自动渲染，条件搜索）
const Search = async () => {
    loading = true
    const params = getParams()
    console.log("已执行params：", params)
    try {
        // 获取生产计划列表数据
        const result = await ProductPlanSearch(params)
        if (result.status === 0) {
            console.log("detailTableData有值:", detailTableData)
            detailTableData.value = result.rows || []
            inventoryTotal.value = result.total || 0
            console.log("inventoryTotal当前条数：", inventoryTotal.value)
        } else {
            detailTableData.value = []
            inventoryTotal.value = 0
            ElMessage.error(result.msg || '查询失败')
        }
    } catch (error) {
        console.error('查询异常:', error)
        detailTableData.value = []
        inventoryTotal.value = 0
    } finally {
        loading = false
    }
}

// 搜索按钮（复用 Search，并且重置页码）
const SearchList = () => {
    inventoryCurrentPage.value = 1
    Search()
}

// 计算属性：返回去重后的数据
const uniqueProductPlanDetails = computed(() => {
    const seen = new Set()
    return productPlanDetails.value.filter(item => {
        if (!seen.has(item.inventory_Id)) {
            seen.add(item.inventory_Id)
            return true
        }
        return false
    })
})

// 获取订单明细
const showOrderDetailData = async (id) => {
    const result = await ProductPlanSearchListDetail(id)
    productPlanDetails.value = result.rows || [] // 原始数据存储
}

// 订单明细上部分
const showOrderDetail = (row) => {
    productPlanHeader.value = { ...row }
    const orderTypeList = {
        0: '加工',
        1: '返工'
     }
    productPlanHeader.value.orderType = orderTypeList[productPlanHeader.value.orderType]
    detailDialogVisible.value = true
    showOrderDetailData(row.productPlan_Id) // 传主键ID
}

watch(() => detailDialogVisible.value, (val) => {
    document.body.style.overflow = val ? 'hidden' : '';
})

// 初始化
Search()


</script>

<style scoped>
.table-container {
    /* background-color: #ffffff; */
    /* border: 1px solid #ebeef5; */
    border-radius: 10px;
    /* padding: 20px; */
    /* margin-bottom: 30px; */
    /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); */
}

/* 表格滚动容器 */
.table-scroll-wrapper {
    /* height: 500px; */
    /* 固定表格高度 */
    overflow: auto;
    /* 表体滚动 */
}

/* 表头固定 */
/* .el-table th {
    position: sticky;
    top: 0;
    background: #fff;
    z-index: 10;
} */

/* 表格文字居中 */
::v-deep(.el-table th, .el-table td) {
    text-align: center;
}

/* 其他样式保持不变 */
.section-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #333;
    padding-bottom: 6px;
    border-bottom: 2px solid #333;
    display: inline-block;
}
</style>

<style lang="less" scoped>
@import "@/assets/css/index.less";
::v-deep {
    .el-container {
        display: block;
    }
    .el-table thead {
        color: #616161 !important;
    }
    .el-table th.el-table__cell {
        background-color: #f8f8f9 !important;
    }
}
</style>
